<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.searchName" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入指标名称"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-table stripe :data="data.tableData">
        <el-table-column prop="metricsName" label="指标名称" />
        <el-table-column label="附件">
          <template v-slot="scope">
            <el-button size="mini" type="primary" @click="showAttachmentForm(scope.row)">上传附件</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="得分">
          <template v-slot="scope">
            <span v-if="scope.row.status==='已审批'">{{scope.row.score}}</span>
            <span v-else-if="scope.row.status">{{scope.row.status}}</span>
            <span v-else>未提交</span>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <span v-if="scope.row.status === '已审批'" class="approved">{{ scope.row.status }}</span>
            <span v-else-if="scope.row.status" class="highlight">{{ scope.row.status }}</span>
            <span v-else class="highlight">未提交</span>
          </template>
        </el-table-column>
        <el-table-column label="提交时间">
          <template v-slot="scope">
            <span v-if="scope.row.submitTime" class="approved">{{ scope.row.submitTime }}</span>
            <span v-else class="highlight">未提交</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination
          @current-change="load"
          background
          layout="prev, pager, next"
          :page-size="data.pageSize"
          v-model:current-page="data.pageNum"
          :total="data.total"
      />
    </div>

    <!-- 附件上传表单对话框 -->
    <el-dialog title="添加附件" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="70px" style="padding: 20px">
        <el-form-item prop="description" label="备注内容">
          <el-input type="textarea" :rows="4" v-model="data.form.description" placeholder="请输入备注内容"></el-input>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
              class="upload-demo"
              ref="upload"
              :action="uploadUrl"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :on-success="handleSuccess"
              :on-error="handleError"
              :limit="1"
              :accept="'.zip,.rar'">
            <el-button size="small" type="primary">上传附件</el-button>
          </el-upload>
          <span v-if="data.form.attachment" class="attachment-name">{{ data.form.attachment }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAttachment">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style>
.approved {
  border: 1px solid green; /* 绿色边框 */
  color: green; /* 绿色文本 */
  padding: 2px 4px; /* 内边距 */
}
 .highlight {
   border: 1px solid red; /* 红框 */
   color: red; /* 红色文本 */
   padding: 2px 4px; /* 内边距 */
 }
.pending {
  border: 1px solid yellow; /* 黄色边框 */
  color: yellow; /* 黄色文本 */
  padding: 2px 4px; /* 内边距 */
}
</style>

<script setup>
import { reactive } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit } from "@element-plus/icons-vue";

const uploadUrl = import.meta.env.VITE_BASE_URL + "/files/upload";

const data = reactive({
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  searchName: null,
  user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
  form: {
    metricsId: 0,
    description: '',
    attachment: null
  },
  formVisible: false,
});

const load = () => {
  request
      .get("/submit/showme", {
        params: {
          studentId: data.user.id,
          pageNum: data.pageNum,
          pageSize: data.pageSize,
          metricsName: data.searchName,
        },
      })
      .then((res) => {
        if (res.code === "200") {
          data.tableData = res.data?.list || [];
          data.total = res.data?.total;
        }
      });
};

/*华到此一游*/

const update = () => {
  request.put("/submit/update", data.form).then((res) => {
    if (res.code === "200") {
      ElMessage.success("操作成功");
      data.formVisible = false;
      load();
    }
  });
};


const handleFileUpload = (res, file, fileList) => {
  if (res.code === '200') {
    data.form.attachment = res.data; // 更新附件信息
  } else {
    // 处理上传失败情况
    ElMessage.error('附件上传失败');
  }
};

const reset = () => {
  data.searchName = null;
  load();
};
const showAttachmentForm = (row) => {
  data.formVisible = true; // 显示对话框
  if (!row) {
    console.error("Row data is undefined!");
    return;
  }
  data.form = {
    description: '',
    attachment: null,
    id: row.id, // 假设每行数据都有唯一的id
    metricsId: row.metricsId,
    status: row.status // 当前行数据的状态
  };
};


const beforeUpload = (file) => {
  const isValidType = file.type === "application/x-zip-compressed" || file.type === "application/rar";
  if (!isValidType) {
    ElMessage.error("只能上传zip或rar格式的文件");
  }
  return isValidType;
};
const submitAttachment = () => {
  if (data.form.attachment || data.form.description) {
    const api = data.form.status === '未提交'||data.form.status==null ? '/submit/add' : '/submit/update';
    request[api === '/submit/add' ? 'post' : 'put'](api, {
      id: data.form.id, // 如果需要，发送id
      metricsId: data.form.metricsId,
      attachment: data.form.attachment,
      description: data.form.description,
    }).then((res) => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        data.formVisible = false;
        load();
      } else {
        ElMessage.error('操作失败');
      }
    });
  } else {
    ElMessage.error('请填写备注并上传附件');
  }
};
const handleSuccess = (response, file) => {
  if (response && response.data) {
    data.form.attachment = response.data;  // 保存返回的文件URL
    ElMessage.success("附件上传成功");
  } else {
    ElMessage.error("附件上传失败");
  }
};

// 上传失败后处理
const handleError = (err, file) => {
  ElMessage.error("附件上传失败");
};
load();
</script>
